package com.zonski.jbots.desktop.client.entity;

import com.zonski.jbots.client.IndexFactory;
import com.zonski.jbots.engine.Entity;
import com.zonski.jbots.desktop.client.Recolorer;
import com.zonski.jbots.desktop.client.ImageUtilities;
import com.zonski.jbots.desktop.client.recolor.ByteSwapRecolorer;
import com.zonski.jbots.desktop.client.recolor.TwoByteSwapRecolorer;
import com.zonski.jbots.desktop.client.recolor.GreyRecolorer;

import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: Chris Glover
 * Date: Oct 15, 2003
 * Time: 5:28:23 PM
 * To change this template use Options | File Templates.
 */
public class LayerImageFactory extends ImageFactory
{
    public static final Recolorer[] RECOLORER = {
        new GreyRecolorer(),
        null,
        //new ByteSwapRecolorer(1, 2),
        //new ByteSwapRecolorer(0, 2),
        new TwoByteSwapRecolorer(2, 1, 0),
        new TwoByteSwapRecolorer(2, 2, 0),
        new TwoByteSwapRecolorer(2, 2, 1)
    };
    private Image[][][] images;
    private int offset;

    public LayerImageFactory(Image[][] images, int offset, IndexFactory indexFactory, Component component)
    {
        this(convertImages(images, component), offset, indexFactory);
    }

    public LayerImageFactory(Image[][][] images, int offset, IndexFactory indexFactory)
    {
        super(images[0], indexFactory);
        this.images = images;
        this.offset = offset;
    }

    public Image getImage(Entity entity)
    {
        // the first layer is grey
        int layerId = entity.layerId - this.offset + 1;
        Image image;
        if(layerId <= 0 || layerId >= images.length)
        {
            image = super.getImage(entity);
        }else{
            image = super.getImage(entity, this.images[layerId], this.indexFactory);
        }
        return image;
    }

    public Image getImage(int layerId)
    {
        return this.images[layerId+1][0][0];
    }

    private static final Image[][][] convertImages(Image[][] images, Component component)
    {
        Image[][][] recolored = new Image[RECOLORER.length][][];
        for(int i=0; i<RECOLORER.length; i++)
        {
            Recolorer recolorer = RECOLORER[i];
            if(recolorer == null)
            {
                recolored[i] = images;
            }else{
                recolored[i] = new Image[images.length][];
                for(int j=0; j<images.length; j++)
                {
                    recolored[i][j] = new Image[images[j].length];
                    for(int k=0; k<images[j].length; k++)
                    {
                        recolored[i][j][k] = ImageUtilities.recolorImage(images[j][k], component, recolorer);
                    }
                }
            }
        }
        return recolored;
    }
}
